﻿using System.Collections.Generic;
using System.Data;
using System.Linq;
using viBook.Models;

namespace viBook.Repositories
{
    public class BookContentTagRepository : IBookContentTagRepository
    {
        private readonly viBookContext _context = new viBookContext();


        public BookContentTagRepository()
        {
            _context = new viBookContext();
        }

        #region IBookContentTagRepository Members

        public IQueryable<BookContentTags> All
        {
            get { return _context.BookContentTags; }
        }

        public BookContentTags Find(int id)
        {
            return _context.BookContentTags.Find(id);
        }

        public void InsertOrUpdate(BookContentTags bookContentTag)
        {
            if (bookContentTag.Id == default(int))
            {
               var contentTag = _context.ContentTags.Find(bookContentTag.ContentTagId);
                if (contentTag != null)
                {
                    contentTag.NumberOfBook++;
                    Save();
                }
                _context.BookContentTags.Add(bookContentTag);
            }
            else
            {
                _context.Entry(bookContentTag).State = EntityState.Modified;
            }
            Save();
        }

        public void Delete(int id)
        {
            var bookContentTag = _context.BookContentTags.Find(id);
            if (bookContentTag == null) 
                return;
            var contentTag = _context.ContentTags.Find(bookContentTag.ContentTagId);
            if (contentTag != null)
            {
                contentTag.NumberOfBook--;
                Save();
            }
            _context.BookContentTags.Remove(bookContentTag);
            Save();
        }

        public void Save()
        {
            _context.SaveChanges();
        }

        public void DeleteAllTagByBookId(int id)
        {
            List<int> listContentTagId = _context.BookContentTags.Where(ct => ct.BookId == id).Select(ct => ct.Id).ToList();
            foreach (int contentTagId in listContentTagId)
            {
                Delete(contentTagId);
            }
            Save();
        }

        #endregion

        public IEnumerable<string> FindCategories(string criteria, int limit)
        {
            return _context.Categories.
                Where(c => c.CategoryName.ToLower().Contains(criteria.ToLower())).
                Take(limit).
                Select(c => c.CategoryName);
        }
    }

    public interface IBookContentTagRepository
    {
        IQueryable<BookContentTags> All { get; }
        BookContentTags Find(int id);
        void InsertOrUpdate(BookContentTags bookContentTags);
        void Delete(int id);
        void Save();
        void DeleteAllTagByBookId(int id);
    }
}